package com.chungkui.check.handler.insidecheck.impl;

import com.chungkui.check.core.bean.CheckResult;
import com.chungkui.check.expression.MatchExpression;
import com.chungkui.check.handler.insidecheck.InsideType;
import com.chungkui.check.handler.insidecheck.InsideCheckFactory;
import com.chungkui.check.handler.insidecheck.InsideCheck;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;

/**
 * @author jason
 * @date 2020/3/28
 */
public class IteratorInsideCheckImpl implements InsideCheck {
    private final Logger log = LoggerFactory.getLogger(IteratorInsideCheckImpl.class);

    @Override
    public CheckResult check(Object field, List<MatchExpression> matchExpressions) {
        log.info("Iterator checkField  field:{}, matchExpressions:{}", field, matchExpressions);
        if (CollectionUtils.isNotEmpty(matchExpressions)) {
            Iterable iterable = (Iterable) field;
            CheckResult result = checkIterator(matchExpressions, iterable.iterator());
            if (!result.ifPass()) {
                return result;
            }
        }
        return new CheckResult(true);
    }

    private CheckResult checkIterator(List<MatchExpression> matchExpressions, Iterator params) {
        if (CollectionUtils.isNotEmpty(matchExpressions) && params != null) {
            while (params.hasNext()) {
                Object data = params.next();
                CheckResult result = InsideCheckFactory.check(data, null, matchExpressions);
                if (!result.ifPass()) {
                    return result;
                }
            }
        }
        return new CheckResult(true);
    }

    @Override
    public boolean suport(Object field, InsideType type) {
        return field instanceof Iterable;
    }

}
